import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';
import type { ErrorType } from 'utils/types/response';
import { BusinessException } from '../filter/business-exception/business.exception';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    let errorCode = status;
    let message = exception.message;

    // 处理业务异常
    if (exception instanceof BusinessException) {
      const error = exception.getResponse() as {
        code: number;
        message: string;
      };
      errorCode = error['code'];
      message = error['message'];
    }

    response.status(status).json({
      statusCode: status,
      errorCode,
      timestamp: new Date().toISOString(),
      path: request.url,
      message,
    } as ErrorType);
  }
}
